import os
import time
import pyautogui, pyperclip
# os.system(r'"C:\Program Files (x86)\onecloud\onecloud.exe"')
from urllib import request
from urllib.error import URLError
from lxml import html
import sys


url = 'https://www.ygdy8.com/html/tv/hytv/20181229/57989.html'


class LinkItem():
    def __init__(self, url, title):
        self.url = url
        self.title = title

    def get_url(self):
        return self.url

    def get_title(self):
        return self.title

def catch_links():
    try:
        resp = request.urlopen(url)
        print(resp.status)
        body = resp.read().decode("gb2312")
        selector = html.fromstring(body)    
        links = selector.xpath('//*[@id="Zoom"]//table//a')
        # print(html.tostring(links[0]))
        # print(links[0].xpath('./@href'))

        # items = []
        # for i in range(len(links)):
        #     items.append(LinkItem(links[i].xpath('./@href'), links[i].xpath('./text()')))
        
        # print(len(items))

        itemsx = [LinkItem(x.xpath('./@href')[0], x.xpath('./text()')[0]) for x in links]
        print(len(itemsx))
        return itemsx
    except URLError as e:
        print('err:', e)
        return []

# 调起玩客云程序界面
def invokeWankeyun():
    os.system(r'"C:\Program Files (x86)\onecloud\onecloud.exe"')
    time.sleep(1)

# pyautogui
#防止失控
pyautogui.FAILSAFE = True

# x,y = pyautogui.position()
# print('%s, %s' % (x, y))

def assertLocation(location, pixel):
    img = pyautogui.screenshot('screenshot.png')
    return img.getpixel((location)) == pixel

# 玩客云
# "云添加"按钮位置：730，220  可点击颜色值（0，142，254）
def click_cloud_add():
    n = 3
    while n > 0: 
        if assertLocation((730, 220), (0, 142, 254)):
            # 鼠标移动到“云添加”按钮上面
            pyautogui.moveTo(730, 220)
            # 鼠标单击
            pyautogui.click()
            # print('点击了“云添加”按钮')
            moveToDef()

            time.sleep(1)
            return True
        else:
            print('"云添加"按钮不可点击，重新尝试')
            n = n - 1
    print('"云添加"按钮尝试点击3次失败')
    return False

# "云添加" 弹框
def paste_download_url_to_dialog(downloadUrl):
    if assertLocation((725, 345), (136, 183, 252)):
        # print("正确弹出云添加对话框")
        #鼠标移动到输入框内，点击一下
        pyautogui.moveTo(725, 432)
        pyautogui.click()
        time.sleep(0.5)
        moveToDef()
        # 放入剪贴板
        pyperclip.copy(downloadUrl)
        # ctrl + v
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(1)
        return True
    else:
        # print('对话框未弹出')
        return False


# "云添加"弹框底部按钮
def click_cloud_dialog_add():
    if assertLocation((1084, 633), (60, 168, 255)):
        # print('添加到玩客云')
        pyautogui.moveTo(1084, 633)
        pyautogui.click()
        time.sleep(2)
        moveToDef()
        #这里需要解析，所以耗时长些
        return True
    else:
        pyautogui.press('esc')
        return False


# 任务弹框
def click_task_dialog_add():

    if assertLocation((1209, 676), (195,198,255)):
        # print('添加')
        pyautogui.moveTo(1209, 676)
        pyautogui.click()
        moveToDef()
        while assertLocation((591,261), (56, 136, 254)):
            time.sleep(1)
        
        # print('添加成功')
        return True
    else:
        # print('不能点击任务添加按钮，放弃')
        pyautogui.press('esc')
        if assertLocation((725, 345), (136, 183, 252)):
            pyautogui.press('esc')
        
        return False

def moveToDef():
    pyautogui.moveTo(200, 800)

if __name__ == '__main__':
    links = catch_links()
    size = len(links)
    if size > 0:
        # 调起玩客云客户端
        invokeWankeyun()
        # 遍历下载地址
        # url = links[10].get_url()
        # print(url)
        for i in range(10, size):
            suc = False
            if click_cloud_add() == True:
                if paste_download_url_to_dialog(links[i].get_url()) == True:
                    if click_cloud_dialog_add() == True:
                        suc = click_task_dialog_add()
                    else:
                        pass
                else:
                    pass
            else:
                pass
            
            print(links[i].get_title(), "添加任务", "成功" if suc == True else "失败")



